var express = require('express');
var router = express.Router();
const path = require('path');
const fs = require('fs');
// 上传模块
const multer = require('multer');
const upload = multer({
	dest: path.join(__dirname, '../../public/file/essay'),
});
// sql
const query = require('../mysql');

// 获取
router.get('/', async (req, res) => {
	let { pagenum, pagesize } = req.query.queryInfo;
	let inputQuery = req.query.queryInfo.query;
	// let searchType = req.query.queryInfo.searchType;
	let searchType = req.query.searchType;
	let { username } = req.query;
	console.log(username);
	// 分页效果
	let result;
	// console.log('inputQuery', inputQuery);
	if (inputQuery == '') {
		let sqlStr = `select * from award where awardee like ? limit ${
			(pagenum - 1) * pagesize
		},${pagesize}`;
		result = await query(sqlStr, [`%${username}%`]);
	} else {
		let sqlStr = `select * from award where ${searchType} like ? and awardee like ? limit ${
			(pagenum - 1) * pagesize
		},${pagesize}`;
		result = await query(sqlStr, [`%${inputQuery}%`, `%${username}%`]);
	}

	// 查询总数量
	let sqlStr1 = `select count(*) from essay`;
	let result1 = await query(sqlStr1);

	// 搜索功能
	res.send({ status: 200, result, total: result1[0]['count(*)'] });
});

let awardAddForm;

// 添加
router.post('/', async (req, res) => {
	res.send({ status: 100, message: '创建获奖信息成功' });
});

router.post('/upload', upload.single('file'), async (req, res, next) => {
	file = req.file;
	saveAward(file, req, res);
});

async function saveAward(file, req, res) {
	let {
		name,
		// 获奖作者
		awardee,
		// 第一获奖人类型
		first_awardee_type,
		// 作者所属单位
		awardee_unit,
		// 成果名称
		achievement_name,
		// 下达单位
		release_unit,
		// 获奖人数
		awardee_num,
		// 发证单位
		award_unit,
		// 获奖时间
		award_time,
		// 获奖级别
		award_category,
		// 获奖等级
		award_level,
		// 学科门类
		subject_classification,
		// 成果形式
		achievement_type,
		// 项目来源
		project_source,
		// 奖励类别
		award_type,
		// 附件
		awardfile,
		// 审批状态
		status,
		// 备注
		remarks,
	} = awardAddForm;
	let extName = file.originalname.split('.')[1];
	// console.log(extName);
	let wordPath = path.join(
		__dirname,
		`../../public/file/award/${name}.${extName}`
	);
	let rs = fs.createReadStream(file.path);
	let ws = fs.createWriteStream(wordPath);

	rs.pipe(ws);

	fs.unlink(file.path, (err) => {
		if (err) console.log(err);
	});

	let sqlStr = `insert into award(name,awardee,first_awardee_type,awardee_unit,achievement_name,release_unit,awardee_num,award_unit,award_time,award_category,award_level,subject_classification,achievement_type,project_source,award_type,status,awardfile,remarks) values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`;

	let result = await query(sqlStr, [
		name,
		awardee,
		first_awardee_type,
		awardee_unit,
		achievement_name,
		release_unit,
		awardee_num,
		award_unit,
		award_time,
		award_category,
		award_level,
		subject_classification,
		achievement_type,
		project_source,
		award_type,
		status,
		`/file/award/${name}.${extName}`,
		remarks,
	]);

	res.send({ status: 200, message: 'upload award success' });
}

// 修改获奖
let awardEditForm;
router.post('/edit', async (req, res) => {
	awardEditForm = req.body.awardEditForm;
	isUploadFile = req.body.isUploadFile;
	if (isUploadFile) {
		return res.send({ status: 100, message: '创建获奖信息成功' });
	} else {
		let {
			name,
			awardee,
			first_awardee_type,
			awardee_unit,
			achievement_name,
			release_unit,
			awardee_num,
			award_unit,
			award_time,
			award_category,
			award_level,
			subject_classification,
			achievement_type,
			project_source,
			award_type,
			status,
			remarks,
			awardfile,
		} = awardEditForm;

		let extName = awardfile.split('.')[1];

		let oldPathName = path.join(__dirname, `../../public${awardfile}`),
			newPathName = path.join(
				__dirname,
				`../../public/file/award/${name}.${extName}`
			);

		fs.rename(oldPathName, newPathName, async (err) => {
			if (err) throw err;
			let sqlStr = `update award set name =?,awardee =?,first_awardee_type =?,awardee_unit =?,achievement_name =?,release_unit =?,awardee_num =?,award_unit =?,award_time =?,award_category =?,award_level =?,subject_classification =?,achievement_type =?,project_source =?,award_type =?,status =?,remarks =?,awardfile = ? where id = ?`;

			let result = await query(sqlStr, [
				name,
				awardee,
				first_awardee_type,
				awardee_unit,
				achievement_name,
				release_unit,
				awardee_num,
				award_unit,
				award_time,
				award_category,
				award_level,
				subject_classification,
				achievement_type,
				project_source,
				award_type,
				status,
				remarks,
				`/file/award/${name}.${extName}`,
				awardEditForm.id,
			]);
			res.send({ status: 200, message: 'success' });
		});
	}
});
router.post('/edit/upload', upload.single('file'), async (req, res) => {
	file = req.file;
	saveEditFile(file, req, res);
});

async function saveEditFile(file, req, res) {
	let {
		name,
		awardee,
		first_awardee_type,
		awardee_unit,
		achievement_name,
		release_unit,
		awardee_num,
		award_unit,
		award_time,
		award_category,
		award_level,
		subject_classification,
		achievement_type,
		project_source,
		award_type,
		status,
		remarks,
		awardfile,
	} = awardEditForm;

	let extName = file.originalname.split('.')[1];
	// console.log(extName);
	let wordPath = path.join(
		__dirname,
		`../../public/file/award/${name}.${extName}`
	);

	let rs = fs.createReadStream(file.path);
	let ws = fs.createWriteStream(wordPath);

	rs.pipe(ws);

	fs.unlink(file.path, (err) => {
		if (err) console.log(err);
	});
	let prevFile = path.join(__dirname, `../../public${awardfile}`);
	fs.unlink(prevFile, (err) => {
		if (err) console.log(err);
	});

	let sqlStr = `update award set name =?,awardee =?,first_awardee_type =?,awardee_unit =?,achievement_name =?,release_unit =?,awardee_num =?,award_unit =?,award_time =?,award_category =?,award_level =?,subject_classification =?,achievement_type =?,project_source =?,award_type =?,status =?,remarks =?,awardfile = ? where id = ?`;

	let result = await query(sqlStr, [
		name,
		awardee,
		first_awardee_type,
		awardee_unit,
		achievement_name,
		release_unit,
		awardee_num,
		award_unit,
		award_time,
		award_category,
		award_level,
		subject_classification,
		achievement_type,
		project_source,
		award_type,
		status,
		remarks,
		`/file/award/${name}.${extName}`,
		awardEditForm.id,
	]);
	res.send({ status: 200, message: 'success' });
}

// 删除获奖
// 删除项目
router.delete('/', async (req, res) => {
	let reqQuery = req.query;

	let prevFile = path.join(__dirname, `../../public${reqQuery.awardfile}`);
	fs.unlink(prevFile, (err) => {
		if (err) console.log(err);
	});
	// console.log(query);
	let sqlStr = `delete from award where id = ?`;
	let result = query(sqlStr, [reqQuery.id]);
	if (!result) {
		res.send({ status: 404, message: 'delete faile' });
	}
	res.send({ status: 200, message: 'delete suceess' });
});
module.exports = router;
